package com.mt.fpb.controller;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.fpb.enums.ResponseCode;
import com.mt.fpb.mapper.WxProductMapper;
import com.mt.fpb.mapper.WxProductOrderMapper;
import com.mt.fpb.model.WxProduct;
import com.mt.fpb.model.WxProductOrder;
import com.mt.fpb.model.vo.CommonResult;
import com.mt.fpb.utils.ParseXml;

import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.QRCodePayQueryRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.Base64;
import com.vbao.service.trade.utils.TradeCodeEnum;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;


/**
     * @Description: TODO(用一句话描述该文件做什么)
     * @author jackliu
     * @date 2017年4月17日 上午11:43:14
     * @version V1.0
     */

@RestController
@RequestMapping("/pay")
public class VbaoQueryOrderController {

    @Autowired
    private WxProductOrderMapper wxProductOrderMapper;


    @Autowired
    private WxProductMapper wxProductMapper;

    /**
     * 支付查询接口
     * @param
     */
    @PostMapping("getPayResult")
        public CommonResult getPayResult (HttpSession  httpSession) {
        /** 1.字符集UTF-8 固定值不变 */

        String InputCharset = "UTF-8";
        /** 2.微保分配的商户号(生产会变) */
        String customerNo = "202108240001";
        /** 3.微保分配的商户密钥(生产会变) */
        String key = "LgG9TWEY1r5ezE8KdSmz";
        /** 4.访问服务地址(生产会变) */
        //
        //String requestDfPayXmlurl = "http://120.27.167.200:8080/vbaoPay/cust/payService/QueryOneQRCodePay";//测试地址
        String requestDfPayXmlurl = "http://pay.chinavbao.com/vbaoPay/cust/payService/QueryOneQRCodePay";

        String id= (String) httpSession.getAttribute("id");
        System.out.println("拿到的Id:"+id);
        //查询支付时间
        String  orderNo= (String) httpSession.getAttribute("id");
        System.out.println("orderNO:"+orderNo);
//     WxProductOrder wxProductOrder = wxProductOrderMapper.selectById(orderNo);
//        if(wxProductOrder==null){
//            return CommonResult.fail(405,"没有该数据");
//        }
//        Date date = wxProductOrder.getStartTime();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMdd");
//        String paydate = dateFormat.format(date);
//        System.out.println(paydate);

        //现在的时间
        Date date=new Date();
        SimpleDateFormat  dateFormat=new SimpleDateFormat("YYYYMMdd");
        String paydate= dateFormat.format(date);
        System.out.println("当前的时间:"+paydate);

        /** 5.发送报文信息 */
        QRCodePayQueryRequest cashierDeskPayQueryRequest = new QRCodePayQueryRequest();

        cashierDeskPayQueryRequest.setVersion("6.0");
        cashierDeskPayQueryRequest.setSignType("MD5");
        cashierDeskPayQueryRequest.setInputCharset(InputCharset);
        cashierDeskPayQueryRequest.setCustomerNo(customerNo);
        cashierDeskPayQueryRequest.setOrderNo(orderNo);
        cashierDeskPayQueryRequest.setPayDate(paydate);

        VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();

        // 组装发送报文
        TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(cashierDeskPayQueryRequest, key, InputCharset, TradeCodeEnum.ONEQRCOCE_PAY_QUERY.getCode());
        System.out.println("发送明文报文:" + tradeRequestXml.getOriRequestXml());
        System.out.println("发送密文报文:" + tradeRequestXml.getRequestXml());
        Map<String,String> map=null;
        if (tradeRequestXml.getErrMsg() == null) {
            // 获取返回报文
            String returnDKPayxml = vbaoChargeSystemHandler.http(requestDfPayXmlurl, tradeRequestXml.getRequestXml(), InputCharset);
            System.out.println("返回密文报文" + returnDKPayxml);
            if (null != returnDKPayxml && returnDKPayxml.length() > 0) {
                String returnOriDKPayxml = "";// 返回明文报文
                try {
                    // 进行解密
                    returnOriDKPayxml = Base64.decode(returnDKPayxml, InputCharset);
                    System.out.println("解密后报文" + returnOriDKPayxml);
                    // 进行验签
                    if (null != returnOriDKPayxml && returnOriDKPayxml.length() > 0) {
                        boolean flag = vbaoChargeSystemHandler.verifySignature(returnOriDKPayxml, key, InputCharset);
                        if (flag) {
                            System.out.println("验签正确");
                            // 汉字的解码
                            String returnXml = URLDecoder.decode(returnOriDKPayxml, InputCharset);
                             map = ParseXml.parseNotifyUrlXml(returnXml);

                             if(id!=null){
                                 System.out.println(map);
                                 //更新订单信息
                                 //String orderNo = (String) map.get("OrderNo");
                                 System.out.println("orderNo:"+orderNo);
                                 String payTimeStr = (String) map.get("PayTime");
                                 String payMoneyStr = (String) map.get("OrderAmount");
                                 System.out.println("payMoneyStr:"+payMoneyStr);
                                 float payMoney= Float.parseFloat(payMoneyStr);
                                 System.out.println("payMoney:"+payMoney);
                                 //获取报文中返回过来的支付状态
                                 String status = (String) map.get("PayStatus");
                                 System.out.println("报文返回的支付状态status:"+status);
                                 if("0".equals(status)){
                                     return CommonResult.fail(300,"请重试");
                                 }


                                 StringBuffer sb = new StringBuffer(payTimeStr);
                                 String productName = (String) map.get("productName");
                                 String id1= (String) map.get("Ext1");
                                 System.out.println("id1:"+id1);


                                 sb.insert(4,"-").insert(7,"-").insert(10," ").insert(13,":")
                                         .insert(16,":");
                                 System.out.println("sb:"+sb);
                                 //根据报文中的产品名称查询产品表
                                 QueryWrapper<WxProduct> queryWrapper = new QueryWrapper();
                                 queryWrapper.eq("product_id",id1);
                                 WxProduct wxProduct = wxProductMapper.selectOne(queryWrapper);
                                 long lockTime  = wxProduct.getLockTime();
                                 System.out.println("lockTime:"+lockTime);

                                 //再将转换好的stringBuffer转成string
                                 String s = sb.toString();
                                 System.out.println("转换前的payTime:"+s);
                                 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                 Date payTime = null;
                                 try {
                                     payTime = simpleDateFormat.parse(s);
                                     System.out.println("转换后payTime:"+payTime);
                                     Calendar calendar = Calendar.getInstance();
                                     calendar.setTime(payTime);
                                     calendar.add(Calendar.DATE,1);
                                     calendar.set(Calendar.HOUR_OF_DAY,0);
                                     calendar.set(Calendar.MINUTE,0);
                                     calendar.set(Calendar.SECOND,0);
                                     Date effectiveTime = calendar.getTime();
                                     long payTimes=effectiveTime.getTime();
                                     long timps=payTimes+(lockTime*24*60*60*1000);
                                     //结束时间
                                     Date endTime=new Date(timps);

                                     WxProductOrder wxProductOrder = new WxProductOrder();
                                     wxProductOrder.setOrderStatus(status);
                                     //更新的开始时间
                                     wxProductOrder.setStartTime(payTime);
                                     //更新支付金额
                                     wxProductOrder.setPayMoney(payMoney);
                                     //更新生效时间
                                     wxProductOrder.setEffectiveTime(effectiveTime);
                                     //订单开始时收益金额就等于支付金额
                                     wxProductOrder.setOrderMoney(payMoney);
                                     //更新结束时间
                                     wxProductOrder.setEndTime(endTime);
                                     QueryWrapper<WxProductOrder> q = new QueryWrapper<>();
                                     q.eq("id",orderNo);
                                     //解析后，更新数据库中的订单状态
                                     int result = wxProductOrderMapper.update(wxProductOrder,q);
                                     System.out.println(result);
                                     if(result==1){
                                         //清空session
                                         httpSession.removeAttribute("id");
                                         System.out.println("删除后的id:"+httpSession.getAttribute("id"));
                                     }

                                 } catch (ParseException e) {
                                     e.printStackTrace();
                                 }
                             }


                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    System.out.println("解析密文报文有误:" + e.getMessage());
                }
            }
        } else {
            System.out.println(tradeRequestXml.getErrMsg());
        }
       return  CommonResult.success(map);
    }

}
